package sg.simple.snmp.util;

import java.io.IOException;

import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;

public class test {
	
	
	static String SYSTEM_DESCRIPTION = "1.3.6.1.2.1.1.1.0";
	static String NETWORK_UPTIME = "1.3.6.1.2.1.1.3.0";
	static String HOST_UP_TIME = "1.3.6.1.2.1.25.1.1.0";
	static String CONTACT_PERSON_FOR_THE_SYSTEM = "1.3.6.1.2.1.1.4.0";
	static String NUMBER_OF_USER_SESSIONS = "1.3.6.1.2.1.25.1.5.0";
	static String NUMBER_OF_PROCESS_CONTEXTS = "1.3.6.1.2.1.25.1.6.0";
	
	public static void main(String[] args) {
		String str = "";
		Address targetAddress = GenericAddress.parse("udp:192.168.0.14/161");
		TransportMapping transport = null;
		try {
			transport = new DefaultUdpTransportMapping();
			Snmp snmp = new Snmp(transport);
			transport.listen();

			// setting up target
			CommunityTarget target = new CommunityTarget();
			target.setCommunity(new OctetString("public"));
			target.setAddress(targetAddress);
			target.setRetries(2);
			target.setTimeout(3000);
			target.setVersion(SnmpConstants.version2c);

			// creating PDU
			PDU pdu = new PDU();
			pdu.add(new VariableBinding(new OID(SYSTEM_DESCRIPTION)));
			pdu.add(new VariableBinding(new OID(NETWORK_UPTIME)));
			pdu.add(new VariableBinding(new OID(HOST_UP_TIME)));
			pdu.add(new VariableBinding(new OID(CONTACT_PERSON_FOR_THE_SYSTEM)));
			pdu.add(new VariableBinding(new OID(NUMBER_OF_USER_SESSIONS)));
			pdu.add(new VariableBinding(new OID(NUMBER_OF_PROCESS_CONTEXTS)));
			

			
			pdu.setType(PDU.GET);

			ResponseEvent response = null;
			response = snmp.send(pdu, target);

			if (response != null && response.getResponse() != null) {

				if (response.getResponse().getErrorStatus() == SnmpConstants.SNMP_ERROR_SUCCESS) {
					PDU pduresponse = response.getResponse();

					for (int i = 0; i < pduresponse.getVariableBindings()
							.size(); i++) {

						str += pduresponse.getVariableBindings().elementAt(i)
								.toString() + '\n';

					}
				} else
					System.out.println(response.getResponse()
							.getErrorStatusText());
			} else
				System.out.println("Timeout.");
			snmp.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("Response=\n" + str);
		System.out.println("Done.");
	}
}
